from targetmonitoring.abstracts.abstract_target_management_client import AbstractTargetManagementClient
import targetmonitoring.utils as utils
import texttable as tt

class ConsoleTargetManagementClient(AbstractTargetManagementClient):
    def __init__(self, csv_file):
        super(ConsoleTargetManagementClient, self).__init__(csv_file)
    
    def _on_display_requested(self, selection_list):
        print "<---------Hedefter----------->"
        for (index,desc) in selection_list.items():
            print "%d- %s"%(index,desc)
            
        self._fire_item_selected(self._get_selection(len(selection_list)))

    @utils.clear_console
    def _on_target_list_display_requested(self, target_list):
        table = tt.Texttable()
        data = [[]]
        
        for target_item in target_list:
            data.append([target_item.id,target_item.name])
        
        table.add_rows(data)
        table.set_cols_align(['r','r'])
        table.header(['ID', 'Name'])
        print table.draw()

    def _on_add_target_display_requested(self, target_object_class):
        new_target_object = target_object_class()
        new_target_object.owner = raw_input("Owner:")
        new_target_object.name = raw_input("Name:")
        new_target_object.start_date = raw_input("Start date:")
        new_target_object.duration = raw_input("Duration(days):")
        new_target_object.initial_status = raw_input("Initial status:")
        
        new_target_object.target_value = None
        while new_target_object.target_value is None:
            target_value = raw_input("Target(meter,kg,hour,minute):")
            try:
                (value, unit) = utils.split_number_unit(target_value)
                new_target_object.target_value = value
                new_target_object.unit = unit
            except ValueError:
                print "Invalid target value entered, try again."
        
        self._fire_target_ready_to_add(new_target_object)
     
    def _on_remove_target_display_requested(self, target_fields):
        entry = raw_input('Enter the target id to remove:')
        try:
            remove_target_id = int(entry)
            self._fire_target_object_to_remove(remove_target_id)
        except ValueError:
            pass
        
    @utils.clear_console
    def _on_exit(self):
        pass      
      
    def _get_selection(self, ra):
        chosen = raw_input("Select "+ str(range(ra)) + ":")
        try:
            chosen = int(chosen)
            if 0<=chosen<ra :
                return chosen
        except ValueError:
            pass
                    
        return None
        

if __name__ == '__main__':
    client = ConsoleTargetManagementClient('/tmp/test01.csv')
    client.start()
